package com.cwx.mychat.utils.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cwx.mychat.entity.enums.ExceptionBizCodeEnum;
import com.cwx.mychat.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 作者： cwx
 * 时间： 2024/9/21 17:43
 * 版本： 1.0
 * 注释：json处理工具类
 */
@Slf4j
public class JsonUtil {

    public static SerializerFeature[] FEATURES = new SerializerFeature[]{SerializerFeature.WriteMapNullValue};

    public static String convertObj2Json(Object obj){
        return JSON.toJSONString(obj, FEATURES);
    }

    public static <T> T convertJson2Obj(String json, Class<T> zClass) throws BusinessException {
        try{
            return JSONObject.parseObject(json, zClass);
        }catch (Exception e){
            log.error("json反序列化异常， json: {}", json, e);
            throw new BusinessException(ExceptionBizCodeEnum.JSON_SERIALIZE_EXCEPTION);
        }
    }

    public static <T> List<T> convertJsonArray2List(String json, Class<T> zClass) throws BusinessException {
        try{
            return JSONArray.parseArray(json, zClass);
        } catch (Exception e){
            log.error("jsonArray序列化异常， json：{}", json, e);
            throw new BusinessException(ExceptionBizCodeEnum.JSON_SERIALIZE_EXCEPTION);
        }
    }
}
